<?php
/**
 * author: cmondor
 * purpose: this script will serve as our registration/product page
 * if you are logged in, you are registered and specific products
 * will appear.  If you are not logged in, it will prompt for
 * email(username) and password to create, along with the
 * notification configuration
 *
 */
include('HTGPage.class.php');

$page = new HTGPage();
/* @var $utils Utils */
$utils = $page->myUtils;
$utils->recordPOST();

/* @var $security HTSecurity */
$security = $page->mySecurity;

/* @var $captcha HTGCaptcha */
$captcha  = $page->myCaptcha;
$errorArray = array();
$displayForm=false;

$displayPayPalBuyNow = true;
if($_REQUEST['from'] == 'ppl') { //if Coming from the paypal with purchase and they are not logged in
	$displayPayPalBuyNow=false;	
}

$newMembershipId=false;
$userId=@$_SESSION['u_id'];
//If user is submitting a form with a submit button
if(@$_REQUEST['submit'] == 'submit') {
	$userRecord=false;

	if(!($page->isLoggedIn())) {
		//If they're not logged in just ignore the registration or login sections

		$myEmail = $_REQUEST['login_email'];
		$myPassword = $_REQUEST['login_password'];

		if(!(empty($myEmail)) && (!(empty($myPassword))) ) {
			//verify login
			if($utils->validEmail($myEmail)) {
				if (!($page->login($myUsername, $myPassword))) {
					//authenticates and logs user in
					array_push($errorArray, 'Sorry, either your email address or your password is incorrect. Don\'t worry, it happens to all of us.  <a href="forgot.php">Click here to reset your password.</a>');
					$displayForm=true;
				} else { //SUCCESS
				}
			} else {
				array_push($errorArray, 'Invalid Email Address.');
				$displayForm=true;
			}
		} else {  //end if trying to login
			//verify registration
			$myEmail = strtolower($_REQUEST['reg_email']);
			$myPassword = $_REQUEST['reg_password1'];
			$myPasswordConfirm = $_REQUEST['reg_password2'];

			//is valid email
			if($utils->validEmail($myEmail)) {
				//does username exist
				$userRecords = $utils->getUser($myEmail);
				if(count($userRecords)) {
					//TODO  if they entered in the right password, log them in.
					//USER ALREADY FOUND
					if(!($page->login($myEmail, $myPassword))) {
						array_push($errorArray, "That email address is already taken.  Please use the \"Existing Account\" section to type in your current email and password.");
						$displayForm=true;
					}
				} else { //USER NOT FOUND OK TO ADD
					//do passwords match
					if(!empty($myPassword) && $myPassword == $myPasswordConfirm) {
						//add user
						$userId = $utils->addUser($myEmail, $myPassword); //should return id
						
						if(!($userId)) {
							error_log(__FILE__ . ':' . __LINE__ . "There was an issue when trying to add the user. USER INSERT FAILURE");
							array_push($errorArray, "For some reason we couldn\'t add a user.");
							$displayForm=true;
						} else { //end if user insert failure  Users INSERT SUCCESS
							if(!($page->login($myEmail, $myPassword))) {
								//THIS SHOULD ALWAYS WORK
								//logging the user in DIRTY
								$_SESSION['login_email'] = $myEmail;
								error_log(__FILE__ . ':' . __LINE__ . ': for some reason we couldn\'t log in right after we added a user that submitted a registration form' );
							}
						} //end else if user added successfully
					} else { //end password matching and user adding
						array_push($errorArray, 'Your passwords didn\'t match.  It\'s OK, just try again.' );
						$displayForm=true;
					}  //end passwords not matching
				} //end else user not found

			} else { //end isvalidemail
				array_push($errorArray, 'Your email address wasn\'t valid.  It\'s OK, just try again.' );
				$displayForm=true;
			}
		} //end else verify registration
	} //end if NOT logged in

	//$userId = $_SESSION['u_id'];
	
	//verify CAPTCHA stuff if we're on a host that has enius.com
	if(stristr($_SERVER['HTTP_HOST'], 'enius.com')) {
		if(!($captcha->validateCaptcha())) {
			$displayForm=true;
			array_push($errorArray, "The two words you typed into our spam filter didn\'t seem to match what was displayed.  <br/>Please type the two funny-looking words in the space right below it to help us verify you\'re not a spammer.  <br />We know it's a pain, but it helps us focus on making better picks for you.");
		}
	}
	
	
	if(count($errorArray) < 1) {
		//don't go any further if things aren't clear up to here. we expect to be logged in and captcha validated.

		//verify membershiptype
		$myMemberShipType = $_REQUEST['membership_type'];
		$membershipTypeRecords = $utils->getMembershipTypeById($myMemberShipType);

		if(!(count($membershipTypeRecords))) {
			//Membership Type NOT found
			error_log(__FILE__ . ':' . __LINE__ . "Membership type not found: " . $myMemberShipType);
			array_push($errorArray, 'We\'re not entirely sure what just happened, but it didn\'t work.  It\'s OK, just try again.' );
		} else { //MEMBERSHIP TYPE FOUND
			$membership = $membershipTypeRecords[0];
			if($membership['mt_duration'] == 0) {
				//membership is free
				$newMembershipId = $utils->addMembership($userId, $myMemberShipType);
			} else {  //end if freemembership

				$newMembershipId = $utils->addMembership($userId, $myMemberShipType);
				//TODO do purchasing code
				//figure out where to send them
				//create PurchaseAttempt
			}
		} //end MEMBERSHIP FOUND
	}//end 	if(!(count($membershipTypeRecords))) {

} else {//end if submitting a FORM
	//if not submitting a form
	$displayForm=true;
}


if(!($displayForm)) { //Membership success
	$page->redirectTo('thankyou.php?m_id=' . $newMembershipId);
} else {
	$page->content .= '<br /><h1 class="myBigTitle">Absolutley Free Registration</h1>';
	
	if(count($errorArray)) {
		foreach ($errorArray as $error) {
			$page->content .= '<span class="error">' . $error . '</span><br />';
		}
	}
	
	if($displayPayPalBuyNow) {
	//Paypal integration created button from paypal Merchant Services section
	$page->content .= '<div id="paypalButton"><h2 style="margin-left: auto; margin-right: auto;">Skip Free Registration</h2><h3>$39 VIP All Access Pass</h3>';
	$page->content .= $utils->get_include_contents('paypal_39_buy_now.html');
	$page->content .= '<br /><h2>That\'s access to every regular and HalfTime pick for both the NFL and NCAA Football for a full 7 days</h2></div>';
	}	
	
	
	$page->content .= '<div id=""><form method="post" id="getitForm" action="' . $_SERVER['PHP_SELF'] . '">';

	//TODO add OR login fields
	if(!($security->isLoggedIn())) {
		$page->content .= '<fieldset><legend>1. Account Information</legend><div id="loginRegDiv">';
// 		$page->content .= '<div id="loginDiv">';
// 		$page->content .= $utils->get_include_contents("getitLoginForm.html");
// 		$page->content .= '</div>';
//		$page->content .= '<div id="regDiv">';
		$page->content .= $utils->get_include_contents("getitRegisterForm.html");
//		$page->content .= '</div>';
//		$page->content .= '<div id="loginOrRegDiv">OR</div>';
		$page->content .= '</div></fieldset>';
	}

	//$page->content .= $utils->get_include_contents("getitNotificationForm.html");
	
	//TODO Product Displayer
	$page->content .= $utils->get_include_contents("defaultProductForm.html");

	$page->preHeadCloseContent .= '<link href="getit.css" rel="stylesheet" type="text/css" />';
	$page->preHeadCloseContent .= $captcha->getCaptchaOptions();


	//Display captcha
	$page->content .= '<fieldset>
	<legend>3. Confirm you\'re not a spammer</legend>';
	$page->content .= $captcha->getCaptchaForm();
	$page->content .= '</fieldset>';
	
	$page->content .= '<fieldset name="submitFieldset">
	<input type="submit" name="submit" value="submit" /></fieldset></form></div>';
	$page->display();
	die();
}

?>